<?php
require_once '../global.inc.php';
Database::connect($HOST, $NAME, $PWD, $DB);
$table 			= "info_activity a,instance_activity b";
// operation操作类型：add、del、query、edit
$operation 		= $_GET["op"];

//展示模板列表
if ($operation=="query") {
	//获取页面信息
	$activityName 	= $_POST["activityName"];
	$leader 		= $_POST["leader"];
	$beginDate 		= $_POST["beginDate"];
	$endDate 		= $_POST["endDate"];
	$status 		= $_POST["status"];
	if(!isset($_GET["p"])){//首次查询
		$condition = "a.activity_id = b.activity_id";
		$tag	   = $_GET["tag"];      //查询后的操作方式（列表，列表编辑）
		if(strlen($activityName)!=0){
			$condition .= " and subject like '%$activityName%'";
		}
		if(strlen($leader)!=0){
			$condition .= " and leader like '%$leader%'";
		}
		if(strlen($beginDate)!=0){
			$condition .= " and travel_date>=str_to_date('$beginDate','%Y-%m-%d')";
		}
		if(strlen($endDate)!=0){
			$condition .= " and travel_date<=str_to_date('$endDate','%Y-%m-%d')";
		}
		if(strlen($status)!=0){
			$condition .= " and status=$status";
		}
		$condition .=" order by instance_id desc";
		$_SESSION["instanceQryWhere"] = $condition;
		$_SESSION["tag"]			= $tag;
	}else{
		$condition = $_SESSION["instanceQryWhere"];
		$tag	   = $_SESSION["tag"];
	}
	//echo $condition;

	$count			= Database::count($table,$condition);	
	$totalRows		= $count[0];				//数据总量
	$currentPage	= $_GET["p"];				//当前页面
	$pageInfo		= array();					//初始化页面信息
	$subpages 		= new SubPages($PAGE_SIZE, $totalRows, $currentPage);	//实例化分页
	$pageInfo 		= $subpages->getPageArray();

	
	//查询本页数据
	$instanceArray 		= Database::findPage($table, $pageInfo["startRow"], $pageInfo["pageSize"],$condition);

	//将分页信息和本页数据写入session
	$_SESSION["pageInfoInstance"]	= $pageInfo;
	$_SESSION["instanceArray"]		= $instanceArray;
	echo "<script>window.location.href='../view/activity/instanceList.php';</script>";
}


//活动实例新增
if ($operation=="add") {
	$activityId		= $_POST["activityId"];
	$saleFee		= $_POST["saleFee"];
	$frontFee		= $_POST["frontFee"];
	$scorePercent	= $_POST["scorePercent"];
	$leader			= $_POST["leader"];
	$travelDate		= $_POST["travelDate"];
	$backDate		= $_POST["backDate"];
	$status			= $_POST["status"]; //0:活动取消  1:活动生成  2：活动结束 3：积分结算
	Database::begin();

	//插入活动模板资料
	$sql = "INSERT INTO instance_activity(activity_id,sale_fee,front_fee,score_percent,leader,travel_date,back_date,status)"
		  ."VALUES ('$activityId','$saleFee','$frontFee','$scorePercent','$leader','$travelDate','$backDate','$status')";
	Database::insert($sql);

	Database::commit();
	Database::end();
	//转向展示页面
	echo "<script>alert('实例生成成功！');</script>";
	echo "<script>window.location.href='../view/activity/instanceQuery.php?tag=q';</script>";
}


//获取某一个活动实例的详细资料
if ($operation=="get") {
	$id				= $_GET["id"];
	$tag			= $_GET["tag"];
	$idName			= "instance_id";

	//查询实例信息
	$instanceInfo		= Database::findById("instance_activity", $idName, $id);
	//查询模板信息
	$activityId			= $instanceInfo["activity_id"];
	$templateInfo		= Database::findById("info_activity", "activity_id", $activityId);
	//查询参与活动的会员信息
	$sql = "select * from member a,member_activity b where a.member_id=b.member_id and b.instance_id=$id";
	$memberActivityArray = Database::find($sql);
	//将取得的活动信息写入session
	$_SESSION["instanceInfo"]	= $instanceInfo;
	$_SESSION["templateInfo"]	= $templateInfo;
	$_SESSION["memberActivityArray"]	= $memberActivityArray;	

	//转向处理页面
	if($tag=="e"){
		echo "<script>window.location.href='../view/activity/instanceDetail.php?op=edit';</script>";
	}else if($tag=="q"){
		echo "<script>window.location.href='../view/activity/instanceDetail.php?op=query';</script>";
	}else if($tag=="s"){
		echo "<script>window.location.href='../view/activity/instanceDetail.php?op=score';</script>";
	}
}

//修改活动实例
if ($operation=="edit") {
	$instanceId		= $_POST["instanceId"];
	$saleFee		= $_POST["saleFee"];
	$frontFee		= $_POST["frontFee"];
	$scorePercent	= $_POST["scorePercent"];
	$leader			= $_POST["leader"];
	$travelDate		= $_POST["travelDate"];
	$backDate		= $_POST["backDate"];

	Database::begin();


	//更新活动资料
	$sql = "update instance_activity set 
				sale_fee 		= '$saleFee'		,
				front_fee 		= '$frontFee'		,
				score_percent	= '$scorePercent'	,
				leader			= '$leader'			,
				travel_date		= '$travelDate'		,
				back_date 		= '$backDate'		";
	$sql .= " where instance_id = $instanceId";

	Database::update($sql);

	Database::commit();
	Database::end();
	//转向展示页面
	echo "<script>alert('活动修改成功！');</script>";
	echo "<script>window.location.href='instanceAction.php?op=get&tag=e&id=$instanceId';</script>";
}

//取消或者恢复或者结束活动
if($operation=="renew"||$operation=="cancel"||$operation=="over"){
	Database::begin();
	$id				= $_GET["id"];
	if($operation=="renew"){//恢复
		$sql	= "update instance_activity set status=1 where instance_id in ($id)";
		Database::update($sql);
		echo "<script>alert('活动恢复成功！');</script>";
		echo "<script>window.location.href='../view/activity/instanceQuery.php?tag=e';</script>";
	}else if($operation=="cancel"){//失效
		//检查是否还有参与该活动的会员，如果还有则必须删除所有会员后才能取消活动
		$result = Database::count("member_activity","instance_id=$id");
		$count	= $result[0];
		if($count==0){
			$sql	= "update instance_activity set status=0 where instance_id in ($id)";
			echo "<script>alert('活动取消成功！');</script>";
			Database::update($sql);
			//转向展示页面
			echo "<script>window.location.href='../view/activity/instanceQuery.php?tag=e';</script>";
		}else{
			echo "<script>alert('该活动下还有参与活动的会员，请先将会员退出该活动，再取消活动！');</script>";
			echo "<script>window.location.href='instanceAction.php?op=get&tag=e&id=$id'</script>";
		}
	}else if($operation=="over"){//结束
		$sql	= "update instance_activity set status=2 where instance_id in ($id)";
		echo "<script>alert('活动成功结束！');</script>";
		Database::update($sql);
		//转向展示页面
		echo "<script>window.location.href='../view/activity/instanceQuery.php?tag=s';</script>";
	}
	Database::commit();
	Database::end();

}
//积分结算
if ($operation=="score") {
	$instanceInfo			= $_SESSION["instanceInfo"];
	$memberActivityArray 	= $_SESSION["memberActivityArray"];
	$templateInfo			= $_SESSION["templateInfo"];
	
	$instanceId				= $instanceInfo["instance_id"];
	$saleFee				= $instanceInfo["sale_fee"];//销售价格
	$scorePercent			= $instanceInfo["score_percent"];//积分比例
	$travelDate				= $instanceInfo["travel_date"];//活动开始时间
	$activityName			= $templateInfo["subject"];//活动名称
	Database::begin();
	foreach ($memberActivityArray as $memberActivity) {
		$payScore		= $memberActivity["pay_score"];//本次抵扣的积分
		$discountFee	= $memberActivity["discount_fee"];//优惠额度
		$memberId		= $memberActivity["member_id"];
		$memberName		= $memberActivity["member_name"];
		$scoreTotal		= $memberActivity["score"];
		if($payScore<0){
			$str = "会员【 ".$memberName."】本次计划抵扣的积分为负数，数据非法，积分结算异常退出！";
			echo "<script>alert('$str');</script>";
			echo "<script>window.location.href='../view/activity/instanceDetail.php?op=score';</script>";
			exit();
		}
		if($payScore>$scoreTotal){
			$str ="会员【".$memberName."】剩余积分小于本次计划抵扣的积分，剩余积分将全部用于抵扣！";
			echo "<script>alert('$str');</script>";
			$payScore = $scoreTotal;
		}
		if($payScore>$saleFee-$discountFee){
			$str ="会员【".$memberName."】本次计划抵扣的积分大于本次活动的售价，只扣除等于售价的积分！";
			echo "<script>alert('$str');</script>";
			$payScore = $saleFee;
		}
		
		//处理本次活动的积分变换
		if ($discountFee!=0) {
			$newScore = 0;  //如果本次存在特价优惠，该会员不产生积分
		}else{
			$newScore = ($saleFee-$payScore)*$scorePercent/100;//本次产生的积分=（销售价格-抵扣的积分）*积分产生比例/100
		}
		$sql = "update member set score = $scoreTotal-$payScore+$newScore where member_id = $memberId";
		Database::update($sql);
		//写入积分日志，一共2条，一条消费，一条产生
		$userName = $_SESSION["user"]["user_name"];
		$changeDate = date('Y-m-d');
		$changeType = 2;	//参与活动
		$changeReason = $travelDate."参加活动".$activityName;//积分改变原因
		$remainScore = $scoreTotal;//为改变前，剩余积分等于总积分
		//消费积分，如果为0，则不写
		if($payScore!=0){
			$changeMethod = 0;	//减少
			$remainScore = $remainScore - $payScore;
			$sql = "insert into log_score(member_id,change_type,change_method,change_score,remain_score,change_reason,change_date,user_name) "
					."values($memberId,'$changeType','$changeMethod','$payScore','$remainScore','$changeReason','$changeDate','$userName')";
			Database::insert($sql);
		}
		//新增积分，如果为0，则不写
		if($newScore!=0){
			$changeMethod = 1;	//增加
			$remainScore = $remainScore + $newScore;
			$sql = "insert into log_score(member_id,change_type,change_method,change_score,remain_score,change_reason,change_date,user_name) "
					."values($memberId,'$changeType','$changeMethod','$newScore','$remainScore','$changeReason','$changeDate','$userName')";
			Database::insert($sql);
		}
		//更新会员本次活动实际抵扣的积分
		$sql = "update member_activity set pay_score=$payScore where instance_id = $instanceId and member_id = $memberId";
		Database::update($sql);
	}
	//更新活动的状态
	$sql = "update instance_activity set status=3 where instance_id = $instanceId";
	Database::update($sql);
	Database::commit();
	Database::end();
	echo "<script>alert('积分结算成功！');</script>";
	echo "<script>window.location.href='../view/activity/instanceQuery.php?tag=q';</script>";
}
//关闭数据库
Database::close();
?>